package com.swotxu.oldwebproject.web.service;

import com.swotxu.oldwebproject.utils.SessionUtil;
import com.swotxu.oldwebproject.web.pojo.ConcurrentUser;
import com.swotxu.oldwebproject.web.pojo.UserInfo;
import com.swotxu.oldwebproject.web.pojo.WebResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Collections;
import java.util.List;

/**
 * @Date: 2019/12/17 21:19
 * @Author: swotXu
 */
@Service
public class LoginService {
    private static final Logger log = LoggerFactory.getLogger(LoginService.class);
//    @Autowired
//    private UserConfig userConfig;

    public WebResult login(UserInfo userInfo, HttpServletRequest request){
        boolean checkLogin = checkLogin(userInfo);
        if(!checkLogin){
            return new WebResult(401, "用户或密码错误！", userInfo);
        }
        HttpSession session = request.getSession();
        userInfo.setToken(request.getRequestedSessionId());
        session.setAttribute(SessionUtil.KEY_USERINFO, userInfo);

        return new WebResult(200, "登录成功", userInfo);
    }

    private boolean checkLogin(UserInfo userInfo){
        log.info("userInfo:{}",userInfo);
//        List<String> userList = userConfig.getUserList();
        List<String> userList = Collections.emptyList();
        log.info("userList:{}", userList);

        for (String userMsg : userList) {
            String[] user = userMsg.split("\\|\\|");
            if(user[1].equals(userInfo.getUsername()) && user[2].equals(userInfo.getPassword())){
                userInfo.setUserid(Integer.valueOf(user[0]));
                return true;
            }
        }
        return true;
    }

    public WebResult getUser(){
        return new WebResult(200, "查询成功！", ConcurrentUser.get());
    }

    public void outLogin(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession(false);
        if(session != null){
            log.info("session clear!");
            session.invalidate();
        }
        try {
            response.sendRedirect(request.getContextPath() + "/");
        } catch (IOException e) {
            log.warn("failed Redirect!", e);
        }
    }

}
